package cn.e4j.modular.api.controller;

import cn.digiwin.wx.utils.WeixinHandler;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.LocalDateUtils;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.GwaService;
import cn.e4j.modular.api.service.Gwat100Service;
import cn.e4j.modular.api.service.Gwat200Service;
import cn.e4j.modular.api.util.CommonUtils;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.service.impl.SystemServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 意向商机指派作业 控制类
 * Created by shixc on 2018/5/5.
 */
@RestController
@RequestMapping("api/wx/gwat200")
public class Gwat200Controller extends ControllerSupport {
    private static Logger logger = LoggerFactory.getLogger(Gwat200Controller.class);

    @Autowired
    Gwat200Service gwat200Service;

    @Autowired
    Gwat100Service gwat100Service;
//
//    @Autowired
//    WXUserService wXUserService;
//
//    @Autowired
//    Gwcm_tDao gwcm_tDao;

    @Autowired
    SystemServiceImpl systemService;

    @Autowired
    GwaService gwaService;

    /**
     * 获取意向订单列表、获取指派数据
     *
     * @return
     */
    @RequestMapping(value = "getGwcmPage")
    public ResponseData getGwcmPage(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        List<Dto> list = new ArrayList<>();
        try {

            inDto.put("GWCMENT", inDto.getString("ENT"));
            inDto.put("GWAA003", currentUser.getACCOUNT());
            list = gwat200Service.getGwcmPage(wapper.getPage(),inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(list);
    }

    /**
     * 获取区域范围
     *
     * @return
     */
    @RequestMapping(value = "getMmreData")
    public ResponseData getMmreData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = gwat200Service.getMmreData(inDto);
        return SUCCESS(list);
    }

    /**
     * 判断是否可以取消指派
     *
     * @param request
     * @param response
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "getGwco")
//    public Dto getGwco(HttpServletRequest request, HttpServletResponse response) {
//        Dto inDto = Dtos.newInDto(request);
//        Dto outDto = Dtos.newOutDto();
////        List<Dto> list = gwat200Service.getGwco(inDto);
////        outDto.put("data", list);
//        return outDto;
//    }

    /**
     * 更新状态
     *
     * @return
     */
    @RequestMapping(value = "update")
    public ResponseData update(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        try {
            gwat200Service.updateData(inDto);
        } catch (Exception e) {
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 商机指派--未指派--单个商品删除
     *
     * @return
     */
    @RequestMapping(value = "wzpDelete")
    public ResponseData wzpDelete(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        try {
            QueryWrapper<GwcmT> wrapper = new QueryWrapper<>();
            wrapper.eq("GWCMENT",inDto.getString("ENT"));
            wrapper.eq("GWCMDOCNO",inDto.getString("GWCMDOCNO"));
            wrapper.eq("GWCMSEQ",inDto.getBigDecimal("GWCMSEQ"));
            new GwcmT().delete(wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS;
    }


    /**
     * 作废
     *
     * @return
     */
    @RequestMapping(value = "toDelete")
    public ResponseData toDelete(@DtoParam DtoWapper wrapper) {
        Dto inDto = wrapper.getDto();
        SysUser currentUser = wrapper.getSysUser();
        List<GwcmT> gwcm_tPOs = new ArrayList<>();
        try {
            JSONObject inJson = JSONObject.parseObject(inDto.getString("obj"));
            JSONArray orders = inJson.getJSONArray("orders");
            for (int i = 0, j = orders.size(); i < j; i++) {
                JSONObject item = orders.getJSONObject(i);
                GwcmT gwcm_tPO = new GwcmT();
                gwcm_tPO.setGWCMENT(currentUser.getDBC());
                gwcm_tPO.setGWCMDOCNO(item.getString("GWCMDOCNO"));
                gwcm_tPO.setGWCMSEQ(item.getBigDecimal("GWCMSEQ"));
                gwcm_tPO.setGWCMACTI("X"); //X:作废
                gwcm_tPO.setGWCMMODU(currentUser.getNAME());
                gwcm_tPOs.add(gwcm_tPO);
            }
            gwat200Service.updateGwcm(gwcm_tPOs);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS;
    }


    /**
     * 派遣--添加商品
     *
     * @return
     */
    @RequestMapping(value = "addGwcmData")
    public ResponseData addGwcmData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        GwcmT gwcm_tPO = new GwcmT();
        List<GwcnT> gwcn_tPOs = new ArrayList<>();
        Dto outDto = new Dto();
        try {
            JSONObject inJson = JSONObject.parseObject(inDto.getString("obj"));

            Dto inDto1 = new Dto();
            inDto1.put("GWCMENT", inDto.getString("ENT"));
            inDto1.put("GWCMDOCNO", inJson.getString("GWCMDOCNO"));
            Dto gwmcswqDto = gwat100Service.getMaxGwcmseq(inDto1);

            gwcm_tPO.setGWCMENT(currentUser.getDBC());
            gwcm_tPO.setGWCMDOCNO(inJson.getString("GWCMDOCNO"));
            gwcm_tPO.setGWCMSEQ(gwmcswqDto.getBigDecimal("GWCMSEQ").add(BigDecimal.ONE)); //
            gwcm_tPO.setGWCMDOCDATE(LocalDateUtils.dateToLocalDate(inJson.getDate("gwcmdocdate")));
            gwcm_tPO.setGWCM001(inJson.getString("GWCM001"));
            gwcm_tPO.setGWCM002(inJson.getString("GWCM002")); // 销售单位
            gwcm_tPO.setGWCM003(inJson.getBigDecimal("GWCM003"));
            gwcm_tPO.setGWCM004(inJson.getBigDecimal("GWCM004"));
            gwcm_tPO.setGWCM005(inJson.getBigDecimal("GWCM003").multiply(inJson.getBigDecimal("GWCM004")));

            /**
             * 添加 GWCM006线人姓名、GWCM007线人手机号码、GWCM008线人微信号、GWCM009意向客户联系人姓名
             * 2018-05-19 by wenchuan.li
             */
            gwcm_tPO.setGWCM006(inJson.getString("GWCM006"));
            gwcm_tPO.setGWCM007(inJson.getString("GWCM007"));
            gwcm_tPO.setGWCM008(inJson.getString("GWCM008"));
            gwcm_tPO.setGWCM009(inJson.getString("GWCM009"));

            gwcm_tPO.setGWCMDATE(LocalDate.now());
            gwcm_tPO.setGWCMACTI("Y"); //已经提交
            gwcm_tPO.setGWCMORIU(currentUser.getID());
            gwcm_tPO.setGWCM010(inJson.getString("GWCM010"));
            gwcm_tPO.setGWCM011(inJson.getString("GWCM011")); //客户编号
//            gwcm_tPO.setGWCM012(new Date());
            gwcm_tPO.setGWCM020(inJson.getString("GWCM020"));
            gwcm_tPO.setGWCM021(inJson.getString("GWCM021"));
            gwcm_tPO.setGWCM022(inJson.getString("GWCM022"));
            gwcm_tPO.setGWCM023(inJson.getString("GWCM023"));
            gwcm_tPO.setGWCM024(inJson.getString("GWCM024"));
            gwcm_tPO.setGWCM025(inJson.getString("GWCM025"));
            gwcm_tPO.setGWCM026(inJson.getString("GWCM026"));
            gwcm_tPO.setGWCM050(inJson.getString("GWCM050"));
            gwcm_tPO.setGWCMMODU(currentUser.getNAME());


            gwat100Service.saveData(gwcm_tPO, gwcn_tPOs);
            outDto.put("order", gwcm_tPO.toDto());
        } catch (Exception e) {
            e.printStackTrace();
           return ERROR;
        }
        return SUCCESS(outDto);
    }


    /**
     * 取消指派
     *
     * @return
     */
    @RequestMapping(value = "cancelZpOrder")
    public ResponseData cancelZpOrder(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        List<GwcmT> gwcm_tPOs = new ArrayList<>();
        String nos = "";
        try {
            JSONObject inJson = JSONObject.parseObject(inDto.getString("obj"));
            JSONArray orders = inJson.getJSONArray("orders");
            Dto sqlDto = new Dto();
            for (int i = 0, j = orders.size(); i < j; i++) {
                JSONObject item = orders.getJSONObject(i);
                String _GWCODOCNO = item.getString("GWCODOCNO");
                sqlDto.put("GWCODOCNO", _GWCODOCNO);
                //判断是否可以取消指派
                Dto countDto = gwat200Service.getGwco(sqlDto);
                if (countDto.getInteger("_COUNT") == 0) {
                    inDto.put("GWCOENT", inDto.getString("ENT"));

                    GwcmT gwcm_tPO = new GwcmT();
                    gwcm_tPO.setGWCMENT(currentUser.getDBC());
                    gwcm_tPO.setGWCMDOCNO(item.getString("GWCMDOCNO"));
                    gwcm_tPO.setGWCMSEQ(item.getBigDecimal("GWCMSEQ"));
                    gwcm_tPO.setGWCMACTI("Y"); //Z已转-->Y已提交
                    gwcm_tPOs.add(gwcm_tPO);

                    gwat200Service.delete(sqlDto, gwcm_tPOs);
                } else {
                    if (nos.indexOf(_GWCODOCNO) == -1) {
                        nos += _GWCODOCNO + "|";
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(nos);
    }
//
    /**
     * 获取经销商信息
     *
     * @return
     */
    @RequestMapping(value = "getGwak")
    public ResponseData getGwak(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        List<Dto> list = new ArrayList<>();
        try {
            inDto.put("ID", currentUser.getID());
            list = gwat200Service.getGwakBy023(wapper.getPage(),inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }

    /**
     * 获取联系人信息
     *
     * @return
     */
    @RequestMapping(value = "getGwaa")
    public ResponseData getGwaa(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = gwat200Service.getGwaa(inDto);
        return SUCCESS(list);
    }

    /**
     * 获取客户分类
     *
     * @return
     */
    @RequestMapping(value = "getGwaf")
    public ResponseData getGwaf(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        return SUCCESS(gwat200Service.getGwaf(inDto));
    }

    /**
     * 获取渠道
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getGwae")
    public ResponseData getGwae(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        return SUCCESS( gwat200Service.getGwae(inDto));
    }

    /**
     * 判断客户手机号码是否存在
     *
     * @return
     */
    @RequestMapping(value = "checkPhone")
    public ResponseData checkPhone(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = gwat200Service.checkPhone(inDto);
        return SUCCESS(list);
    }

    /**
     * 获取产品系列
     *
     * @return
     */
    @RequestMapping(value = "getGwaoData")
    public ResponseData getGwaoData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = gwat200Service.getGwaoData(inDto);
        return SUCCESS(list);
    }

    /**
     * 派单数据 提交
     *
     * @return
     */
    @RequestMapping(value = "yxsjzpSave")
    public ResponseData insert(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        List<GwcoT> gwco_tPOs = new ArrayList<>();
        List<GwcmT> gwcm_tPOs = new ArrayList<>();
        JSONObject inJson = new JSONObject();
        Integer appCode = 200;
        try {
            inJson = JSONObject.parseObject(inDto.getString("obj"));

            JSONArray orders = inJson.getJSONArray("orders");
            String no = "YXDD" + DateUtils.getDate("yyyyMMddHHmmssSSS");
            for (int i = 0, j = orders.size(); i < j; i++) {
                JSONObject item = orders.getJSONObject(i);
                GwcoT gwco_tPO = CommonUtils.toJavaClass(inJson, GwcoT.class);

                gwco_tPO.setGWCOENT(currentUser.getDBC());
                gwco_tPO.setGWCODOCNO(no);
                gwco_tPO.setGWCOSEQ(BigDecimal.valueOf(i + 1));
                gwco_tPO.setGWCODOCDATE(LocalDate.now());


                gwco_tPO.setGWCO001(item.getString("GWCM001"));
                gwco_tPO.setGWCO002(item.getString("GWCM002"));//销售单位
                gwco_tPO.setGWCO003(item.getBigDecimal("GWCM003"));
                gwco_tPO.setGWCO004(item.getBigDecimal("GWCM004"));
                gwco_tPO.setGWCO005(item.getBigDecimal("GWCM003").multiply(item.getBigDecimal("GWCM004")));
                gwco_tPO.setGWCO006(item.getString("GWCM006"));//线人
                gwco_tPO.setGWCO007(item.getString("GWCM007"));//线人手机
                gwco_tPO.setGWCO008(item.getString("GWCM009"));
                gwco_tPO.setGWCO009(item.getString("GWCM010"));
                gwco_tPO.setGWCO010(item.getString("GWCM011"));
                // 地域数据都是对应 客户的  不是经销商的
                gwco_tPO.setGWCO020(item.getString("GWCM020"));//客户地址
                gwco_tPO.setGWCO021(item.getString("GWCM021"));
                gwco_tPO.setGWCO022(item.getString("GWCM022"));
                gwco_tPO.setGWCO023(item.getString("GWCM023"));
                gwco_tPO.setGWCO024(item.getString("GWCM024"));
                gwco_tPO.setGWCO025(item.getString("GWCM025"));
                gwco_tPO.setGWCO026(item.getString("GWCM026"));
                gwco_tPO.setGWCO050(item.getString("GWCM050"));
                gwco_tPO.setGWCO030(item.getString("GWCMDOCNO"));
                gwco_tPO.setGWCO031(item.getBigDecimal("GWCMSEQ"));

                //gwco_tPO.setGWCODATE(new Date());
                gwco_tPO.setGWCODATE(LocalDate.now());
                gwco_tPO.setGWCOACTI("N");
                gwco_tPO.setGWCOORIU(currentUser.getID());
                gwco_tPOs.add(gwco_tPO);

                GwcmT gwcm_tPO = new GwcmT();
                gwcm_tPO.setGWCMENT(currentUser.getDBC());
                gwcm_tPO.setGWCMDOCNO(gwco_tPO.getGWCO030());
                gwcm_tPO.setGWCMSEQ(gwco_tPO.getGWCO031());
                gwcm_tPO.setGWCMACTI("Z"); //已转
                gwcm_tPO.setGWCMDATE(LocalDate.now());
                gwcm_tPOs.add(gwcm_tPO);
            }

            gwat200Service.insert(gwco_tPOs, gwcm_tPOs);


        } catch (Exception e) {
            e.printStackTrace();
            appCode=500;
        }

        if (appCode == 200) {
            Dto gwaaDto = new Dto();
            gwaaDto.put("GWAAENT", inDto.getString("ENT"));
            gwaaDto.put("GWAA004", inJson.getString("GWCO013"));
            List<Dto> sysUser = gwat200Service.getGwaaData(gwaaDto);
            WeixinHandler.sendMsg(sysUser,
                    String.format("有新的指派订单！线人[%s], 线人手机号码[%s]",
                            inJson.getString("GWCO006"),
                            inJson.getString("GWCO007")
                    ));
        }

        return appCode==200?SUCCESS:ERROR;
    }

    /**
     * 经销商保存
     * @return
     */
    @RequestMapping(value = "insertGwak")
    public ResponseData insertGwak(@DtoParam DtoWapper wapper) {
        SysUser currentUser = wapper.getSysUser();
        Dto inDto = wapper.getDto();
        GwakT gwak_tPO = new GwakT();
        GwaklT gwakl_tPO = new GwaklT();
        GwalT gwal_tPO = new GwalT();
        try {
            gwak_tPO = JSON.parseObject(JSON.toJSONString(inDto), GwakT.class);
            gwak_tPO.setGWAKUSER(currentUser.getID());
            gwak_tPO.setGWAKMODU(currentUser.getID());
            gwak_tPO.setGWAKORIU(currentUser.getID());
            gwak_tPO.setGWAKGRUP(currentUser.getORG_ID());
            gwak_tPO.setGWAKORIG(currentUser.getORG_ID());
            gwak_tPO.setGWAKDATE( LocalDate.now());
            gwak_tPO.setGWAKTIME( DateUtils.getTime());
            gwak_tPO.setGWAKENT(currentUser.getDBC());
            gwak_tPO.setGWAK002("1"); // 1.客户、2.厂商、3.两者
            gwak_tPO.setGWAK006("2"); //1.最终客户、2.经销商、3.内部法人、4.其他类
            //gwak_tPO.putGwak007("*");
//            String currency = AppCxt.getParam("sys_currency");
//            gwak_tPO.setGWAK008(currency==null?" ":currency);
            gwak_tPO.setGWAK019(currentUser.getACCOUNT());
            gwak_tPO.setGWAK020("ASIA");
            gwak_tPO.setGWAK021("CN");
            gwak_tPO.setGWAKACTI("Y");
            gwak_tPO.setGWAKORIG(currentUser.getORG_ID());

            // add by wenchuan.li 2018/10/26 13:31
//            Dto sys002Dto = new Dto();
//            sys002Dto.put("ORG_ID",currentUser.getORG_ID());
//            Dto sys002 = systemService.getSys002(sys002Dto);
//            gwak_tPO.setGWAKPLANT(sys002.getString("ID"));//法人
            gwak_tPO.setGWAK056(BigDecimal.ONE);//折扣率

            gwakl_tPO = JSON.parseObject(JSON.toJSONString(inDto), GwaklT.class);
            gwakl_tPO.setGWAKLENT(currentUser.getDBC());
            gwakl_tPO.setGWAKL004(gwakl_tPO.getGWAKL003());
            if (gwakl_tPO.getGWAKL003().length() >= 6) {
                gwakl_tPO.setGWAKL003(gwakl_tPO.getGWAKL003().substring(0, 6));
            } else {
                gwakl_tPO.setGWAKL003(gwakl_tPO.getGWAKL003());
            }
            gwakl_tPO.setGWAKL002("2");

            Dto inDto1 = new Dto();
            inDto1.put("GWAKENT", inDto.getString("ENT"));
            inDto1.put("GWAK001_S",DateUtils.getDate("yyMMdd"));
            Dto dto = gwat100Service.getGwak001(inDto1);

            if (ToolUtil.isNotEmpty(dto) && dto.containsKey("GWAK001")
                    && ToolUtil.isNotEmpty(dto.getString("GWAK001"))
                    && dto.getString("GWAK001").length() == 9) {

                String gwak001 = dto.getString("GWAK001");
                int no = Integer.parseInt(gwak001) + 1;
                String gwak001New = (no > 99999999 ? "" : "0") + String.valueOf(no);
                gwak_tPO.setGWAK001(gwak001New);
                gwakl_tPO.setGWAKL001(gwak001New);
                gwakl_tPO.setGWAKL005(gwak001New);
            } else {
                gwak_tPO.setGWAK001(inDto1.getString("GWAK001_S") + "001");
                gwakl_tPO.setGWAKL001(inDto1.getString("GWAK001_S") + "001");
                gwakl_tPO.setGWAKL005(inDto1.getString("GWAK001_S") + "001");
            }

            gwal_tPO.setGWALUSER(currentUser.getID());
            gwal_tPO.setGWALMODU(currentUser.getID());
            gwal_tPO.setGWALORIU(currentUser.getID());
            gwal_tPO.setGWALGRUP(currentUser.getORG_ID());
            gwal_tPO.setGWALORIG(currentUser.getORG_ID());
            gwal_tPO.setGWALDATE( LocalDate.now());
            gwal_tPO.setGWALTIME( DateUtils.getTime());
            gwal_tPO.setGWALENT(currentUser.getDBC());
            gwal_tPO.setGWAL001(gwak_tPO.getGWAK001());

            Dto d = new Dto();
            d.put("GWAL001",gwak_tPO.getGWAK001());
            d.put("GWALENT", inDto.getString("ENT"));
            gwal_tPO.setGWAL002(gwaService.getGwa002(d));

            gwal_tPO.setGWAL003("Y");
            gwal_tPO.setGWAL010("ASIA");
            gwal_tPO.setGWAL011("CN");
            gwal_tPO.setGWAL012(gwak_tPO.getGWAK022());
            gwal_tPO.setGWAL013(gwak_tPO.getGWAK023());
            gwal_tPO.setGWAL014(gwak_tPO.getGWAK024());
            gwal_tPO.setGWAL015(gwak_tPO.getGWAK025());
            gwal_tPO.setGWAL016(ToolUtil.isNotEmpty(gwak_tPO.getGWAK026()) ? gwak_tPO.getGWAK026(): "*");
            gwal_tPO.setGWAL017(ToolUtil.isNotEmpty(gwak_tPO.getGWAK027())? gwak_tPO.getGWAK027(): "*");
            gwal_tPO.setGWAL018(ToolUtil.isNotEmpty(gwak_tPO.getGWAK028())? gwak_tPO.getGWAK028(): "*");
            gwal_tPO.setGWAL019(ToolUtil.isNotEmpty(gwak_tPO.getGWAK029()) ? gwak_tPO.getGWAK029() : "*");
            gwal_tPO.setGWAL020(ToolUtil.isNotEmpty(gwak_tPO.getGWAK030()) ? gwak_tPO.getGWAK030() : "*");
            gwal_tPO.setGWAL021(gwak_tPO.getGWAK031());
            gwal_tPO.setGWALACTI("Y");

            gwat100Service.saveCustomer(gwak_tPO, gwakl_tPO, gwal_tPO);
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData();
        }
        return SUCCESS;
    }

}
